from peewee import (
    AutoField,
    CharField,
    DateTimeField,
    FloatField, IntegerField,
    Model,
    MySQLDatabase as PeeweeMySQLDatabase,
    ModelSelect,
    ModelDelete,
    chunked,
    fn
)

from vnpy_mysql.mysql_database import DateTimeMillisecondField,db as mysqlDb
from typing import List

class MyTickData(Model):

    # def __init__(self) -> None:
        # print("开始建表MyTickData")
        # mysqlDb.drop_tables([MyTickData])
        # mysqlDb.create_tables([MyTickData])
        

    id: AutoField = AutoField()

    symbol: str = CharField()
    exchange: str = CharField()
    datetime: datetime = DateTimeMillisecondField()

    name: str = CharField()
    volume: float = FloatField()
    turnover: float = FloatField()
    open_interest: float = FloatField()
    last_price: float = FloatField()
    last_volume: float = FloatField()
    limit_up: float = FloatField()
    limit_down: float = FloatField()

    # volume_add: int = IntegerField()
    last_open_interest: int = IntegerField()
    direction: str = CharField()


    open_price: float = FloatField()
    high_price: float = FloatField()
    low_price: float = FloatField()
    pre_close: float = FloatField()

    bid_price_1: float = FloatField()
    ask_price_1: float = FloatField()
    bid_volume_1: float = FloatField()
    ask_volume_1: float = FloatField()

    localtime: datetime = DateTimeField(null=True)

    class Meta:
        database: PeeweeMySQLDatabase = mysqlDb
        indexes: tuple = ((("symbol", "exchange", "datetime"), True),)

mysqlDb.create_tables([MyTickData])

def saveMyTickData(self, data: List) -> bool:
    colums=["name","volume","turnover","open_interest","limit_up",
        "limit_down","open_price","high_price","low_price","pre_close",
        "bid_price_1","ask_price_1","bid_volume_1","ask_volume_1",
        "direction","last_open_interest","last_price","last_volume","datetime"]
# 使用upsert操作将数据更新到数据库中
    with mysqlDb.atomic():
        # MyTickData.bulk_create(ticks,100)
        for c in chunked(data, 50):
            MyTickData.insert_many(c,colums).on_conflict_replace().execute()